var _container;
function loadVideo(playerUrl, autoplay) {
	document.getElementById("youtubeFrame").setAttribute("src", "http://www.youtube.com/embed/" + getYoutubeID(playerUrl) + '?wmode=opaque&autoplay=' + (autoplay?1:0));
}

function searchYoutube(term, container)
{
    try{
	_container = container;
	//document.getElementById(_container).innerHTML = 'Loading YouTube videos ...';

	//create a JavaScript element that returns our JSON data.
	var script = document.createElement('script');
	script.setAttribute('id', 'jsonScript');
	script.setAttribute('type', 'text/javascript');
	script.setAttribute('src', 'http://gdata.youtube.com/feeds/videos?'+
		   'vq=' + encodeURI(term) +
		   '&max-results=7&' +
		   'alt=json-in-script&callback=showMyVideos&' + 
		   'orderby=relevance&sortorder=descending&format=5&fmt=18');

	//attach script to current page -  this will submit asynchronous
	//search request, and when the results come back callback 
	//function showMyVideos(data) is called and the results passed to it
	document.documentElement.firstChild.appendChild(script);
    }
    catch(e){}
}

function getYoutubeID(url)
{
	var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]{11,11}).*/;
	var match = url.match(regExp);
	if (match) if (match.length >= 2)
		return match[2];
	else
		return null;
	
}

function showMyVideos(data)
{
	var html = '<iframe id="youtubeFrame" width="696" height="320" frameborder="0">';
	html += '</iframe>';
    html += '<div id="videoResultsDiv">';
	html += '</div>';
	document.getElementById(_container).innerHTML = html;

	var feed = data.feed;
	var entries = feed.entry || [];
	html = "<table style='width:696px'><tr>";
	for (var i = 0; i < entries.length; i++)
	{
		var entry = entries[i];
		//var playCount = entry.yt$statistics.viewCount.valueOf() + ' views';
		//var lnk = '<a href = \"' + entry.link[0].href + '\">link</a>';
		
		var title = entry.title.$t;
		var thumbnailUrl = entries[i].media$group.media$thumbnail[0].url;
		var playerUrl = entries[i].media$group.media$content[0].url;
		var image = '<td><a href="#" onclick="loadVideo(\'' + playerUrl + '\', true)"><img src="' + thumbnailUrl + '" width="87" height="60" title="' + title + '" /></a></td>';
		html += image;
	}
	if(entries.length > 0)
	{
		loadVideo(entries[0].media$group.media$content[0].url , false);
	}
	document.getElementById(_container).innerHTML += html + "<tr></table>";
}